package com.dongdongshop.mq;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

import java.util.Objects;

//MQ发送者的回调方法
@RocketMQTransactionListener(txProducerGroup = "dk2107-tx-group")
public class MQTransactionCallBack implements RocketMQLocalTransactionListener {

    //执行本地事务的方法
       @Autowired
       private RedisTemplate redisTemplate;
    /**
     *
     * @param message
     * @param arg 传过来的参数(修改订单状态)
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //执行本地事务
        String id = message.getHeaders().getId().toString();
        try{
            System.out.println("执行本地事务（修改订单状态）需要用到的参数" + arg);
            String msg = new String((byte[]) message.getPayload());
            System.out.println("要发送的消息"+msg);

            redisTemplate.boundHashOps("rollBackMsgId").put(id,"1");
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("进入RollBack"+e);
            redisTemplate.boundHashOps("rollBackMsgId").put(id,"2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    //回查方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String id = message.getHeaders().getId().toString();
        String status =(String) redisTemplate.boundHashOps("rollBackMsgId").get(id);
        if (Objects.equals(status,"2")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
